package com.sgcc.pda.ssal.mqtt;

import android.app.Notification;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.sgcc.pda.baselibrary.utils.DeviceUtil;
import com.sgcc.pda.baselibrary.utils.LogUtil;
//import com.sgcc.pda.greendao.entity.Msg;
//import com.sgcc.pda.greendao.entity.NotificationInfo;
//import com.sgcc.pda.greendao.entity.SubscribeInfo;
//import com.sgcc.pda.greendao.entity.message.NoticeMessage;
//import com.sgcc.pda.greendao.entity.message.NoticeMessageDao;
//import com.sgcc.pda.greendao.entity.task.BaseTaskInfo;
//import com.sgcc.pda.greendao.model.BaseTaskInfoModel;
//import com.sgcc.pda.greendao.model.NoticeMessageModel;
//import com.sgcc.pda.greendao.model.NotificationModel;
//import com.sgcc.pda.greendao.model.OfflineMsgModel;
//import com.sgcc.pda.greendao.model.SubscribeInfoModel;
//import com.sgcc.pda.mdrh.app.ZoomApplication;
//import com.sgcc.pda.mdrh.entity.Constants;
//import com.sgcc.pda.mdrh.events.RedDotRefreshEvent;
import com.sgcc.pda.mdrh.log.HzLogSaveUtil;
//import com.sgcc.pda.mdrh.utils.NotificationUtil;
//import com.sgcc.pda.mdrh.utils.TaskInfoConvert;
//import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
//import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * paho框架的mqtt回调接口，此处统一处理推送的消息
 *
 * @author zcj
 * @date 2019/9/4
 */
public class PahoMqttCallback implements MqttCallback {

    private static final String TAG = "mqtt";
    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private static final String BROADCAST_PERMISSION = "com.sgcc.pda.permissions.COMM_BROADCAST";


    @Override
    public void connectionLost(Throwable cause) {
        LogUtil.e(TAG, "connectionLost: " + cause.getMessage());
        HzLogSaveUtil.saveLog("断开连接 connectionLost:  cause==" + cause.getMessage(), HzLogSaveUtil.LogType.MQTT);


    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String content = new String(message.getPayload());
        String time = format.format(new Date());

        LogUtil.e(TAG, "回调收到消息: topic== " + topic + "  content== " + content);
        HzLogSaveUtil.saveLog("回调收到消息: topic== " + topic + "  content== " + content, HzLogSaveUtil.LogType.MQTT);
        /*TODO
        SubscribeInfoModel subscribeInfoModel = new SubscribeInfoModel();
        SubscribeInfo subscribeInfo = subscribeInfoModel.queryByKey(topic);
        if (subscribeInfo != null) {
            List<String> packageList = subscribeInfo.getPackageList();
            for (int i = 0; i < packageList.size(); i++) {
                String pkgName = packageList.get(i);
                OfflineMsgModel offlineMsgModel = new OfflineMsgModel();
                offlineMsgModel.saveOfflineMsg(pkgName, topic, content, time);
            }
        }

        Intent intent = new Intent();
        intent.setAction("web.mqtt.notification." + topic);
        Msg msg = new Msg(time, topic, content);
        intent.putExtra("content", new Gson().toJson(msg));
//        intent.putExtra("time", time);
        ZoomApplication.getInstance().sendBroadcast(intent, BROADCAST_PERMISSION);

        String imei = DeviceUtil.getDeviceIMEI(ZoomApplication.getInstance());
        String userCode = SharepreferenceUtil.getUserCode(ZoomApplication.getInstance());
        String clientId = userCode;// 端对端消息会话标识

        //小红点消息处理逻辑，notification主题是主应用订阅的，没有走aidl接口
        //不走离线逻辑，永远是在线状态。
        if (topic.equals(Constants.TOPIC_NOTIFICATION)) {
            notificationLogic(message);
        }
        // 端对端消息主题
        else if (topic.equals(Constants.TOPIC_MESSAGE + clientId)) {
            noticeLogic(content);
        }
        */
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        LogUtil.d(TAG, "deliveryComplete: ");

    }

    /**
     * 小红点通知处理逻辑
     */
    public void notificationLogic(MqttMessage message) {
        try {
            String content = new String(message.getPayload());
            String time = format.format(new Date());
            /* TODO
            NotificationInfo notificationInfo = new Gson().fromJson(content, NotificationInfo.class);
            NotificationModel notificationModel = new NotificationModel();
            notificationModel.insert(notificationInfo);
            EventBus.getDefault().post(new RedDotRefreshEvent());
            //发送一条系统通知
            Notification notification = new NotificationCompat.Builder(ZoomApplication.getInstance())
                    .setContentTitle(notificationInfo.getTitle())  //设置标题
                    .setContentText(notificationInfo.getContent()) //设置内容
                    .setWhen(System.currentTimeMillis())  //设置时间
                    .setSmallIcon(R.drawable.ic_toggle_on)  //设置小图标
                    .setLargeIcon(BitmapFactory.decodeResource(ZoomApplication.getInstance().getResources(), R.mipmap.ic_launcher)) //设置大图标
                    .build();
            int i = NotificationUtil.getInstance().notifyMsg(notificationInfo);
            Log.e(TAG, "notificationLogic: notifyId == " + i);*/
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e(TAG, "无效notification通知");
        }

    }

    /**
     * 通知消息处理
     *
     * @param content 推送消息
     */
    public void noticeLogic(String content) {
        /*TODO
        NoticeMessage item = new Gson().fromJson(content, NoticeMessage.class);
        if (item != null) {
            // 设置通知接收时间
            item.setTimeLong(System.currentTimeMillis());
            // 设置通知未读
            item.setRead(false);
            // 保存通知消息
            NoticeMessageModel model = new NoticeMessageModel();
            long id = model.insertOrReplace(item);
            LogUtil.e(TAG, "noticeLogic: row id == " + id);
            // 保存工单
            taskLogic(item.getMesDetail());
            if (model.count() > 100) {
                // 超过100条，删除第一条item
                NoticeMessage delete = model.getGreenDao().queryBuilder().limit(1)
                        .orderAsc(NoticeMessageDao.Properties.TimeLong).unique();
                model.delete(delete);
            }

            // 通知列表更新
            EventBus.getDefault().post(item);
            // 工单派发类消息 发送广播通知
            if ("01".equals(item.getMesType())) {
                Intent intent = new Intent("com.sgcc.pda.mdrh.newTaskOrderReceiver");
                intent.putExtra("mesDetail", item.getMesDetail());
                ZoomApplication.getInstance().sendBroadcast(intent, BROADCAST_PERMISSION);
            }


            // 接收到消息，显示通知栏提示
            NotificationInfo info = new NotificationInfo();
            info.setTitle(item.getMesTitle());
            info.setContent(item.getMesContent());
            int i = NotificationUtil.getInstance().notifyP2pMsg(info);
            LogUtil.e(TAG, "noticeLogic: notifyId == " + i);
        }*/
    }


    /**
     * 工单通知处理逻辑
     *
     * @param detail 通知内容包含的工单信息
     */
    public void taskLogic(String detail) {
        /*TODO
        LogUtil.e(TAG, "taskLogic: " + detail);
        if (!TextUtils.isEmpty(detail)) {
            // 工单信息不为空，保存工单
            BaseTaskInfo baseTaskInfo = TaskInfoConvert.convert(detail);
            BaseTaskInfoModel baseTaskInfoModel = new BaseTaskInfoModel();
            long id = baseTaskInfoModel.insertOrReplace(baseTaskInfo);
            LogUtil.e(TAG, "taskLogic: row id == " + id);
        }*/
    }
}
